<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Admin\Controller;

use Admin\Api\DatatreeApi;
use Admin\Api\FreightTemplateApi;
use Admin\Api\UserPictureApi;
use Admin\Api\WxstoreApi;
use Api\Vendor\NetWarehourse\WHPurcharseOrder;
use Common\Model\ProductSkuModel;
use Shop\Api\CategoryApi;
use Shop\Api\CategoryPropApi;
use Shop\Api\GroupOrderApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductAttrApi;
use Shop\Api\ProductFaqApi;
use Shop\Api\ProductGroupApi;

use Shop\Api\ProductPropApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\SkuApi;
use Shop\Api\SkuvalueApi;
use Shop\Api\StoreApi;
use Tool\Api\ProvinceApi;

class ProductController extends AdminController {

    private $store_id;

    public function _initialize(){
        parent::_initialize();
        $this->store_id = session("current_store_id");

        if(empty($this->store_id)){
            $this->store_id = I('get.store_id',0);
            session("current_store_id",$this->store_id);
        }
		//dump($_SESSION);
		if(empty($this->store_id)){
			$uid = session("uid");
			$map = array(
				"uid"=> $uid
			);
			$result = apiCall("Shop/Store/getInfo",array($map));
			if($result['status']){
				$this->store_id = $result['info']['id'];
			}
		}
		if (empty($this->store_id)) {
            $this -> error("缺少店铺ID参数！");
        }

    }

	public function group(){
		if(IS_GET){

			$store_id = I('get.store_id',0);

			$map = array('parentid'=>getDatatree('WXPRODUCTGROUP'));
			$result = apiCall(DatatreeApi::QUERY_NO_PAGING,array($map));
            if(!$result['status']){
				$this->error($result['info']);
			}

			$this->assign("groups",$result['info']);
			$this->assign("store_id",$store_id);

			$this -> display();
		}
	}

	public function deleteGroup(){
		$id = I('id',0);

		$result = apiCall("Admin/Datatree/queryNoPaging", array(array('parentid'=>$id)));
		if(!$result['status']){
			$this->error($result['info']);
		}
		if(is_array($result['info']) && count($result['info']) > 0){
			$this->error("有子级，请先去数据字典中删除所有子级！");
		}

		$result = apiCall("Admin/Datatree/delete", array(array('id'=>$id)));
		if(!$result['status']){
			//删除成功，则删除该分组商品，防止垃圾数据 TODO 事务回滚
			$map = array(
				'g_id' => $id,
			);
			$result = apiCall(ProductGroupApi::DELETE,array($map));
			$this->error($result['info']);
		}

		$this->success("操作成功！");

	}

	public function addGroup(){
		if(IS_GET){
			$this -> display();
		}else{
			$parentid = getDatatree('WXPRODUCTGROUP');
			$result = apiCall(DatatreeApi::GET_INFO,array(array('id' => $parentid)));
			$level = 0;
			$parents = $parentid.',';
			if($result['status'] && is_array($result['info'])){
				$level = intval($result['info']['level'])+1;
				$parents = $result['info']['parents'].$parents;
			}
			$entity = array(
					'name'=>I('name',''),
					'notes'=>I('notes',''),
					'sort'=>I('sort',''),
					'level'=>$level,
					'parents'=>$parents,
					'parentid'=>$parentid,
					'code'=>I('code',''),
					'iconurl'=>I('iconurl',''),
			);

			$result = apiCall("Admin/Datatree/add", array($entity));

			if(!$result['status']){
				$this->error($result['info']);
			}

			$this->success("操作成功！",U('Admin/Product/group'));
		}
	}


	/*public function group(){
		$id = I('id',0);
		if(IS_GET){

			$result = apiCall(ProductApi::GET_INFO,array(array('id'=>$id)));
			if(!$result['status']){
				$this->error($result['info']);
			}

			$this->assign("product",$result['info']);

			$store_id = I('get.store_id',0);

			$map = array('parentid'=>getDatatree('WXPRODUCTGROUP'));

			$result = apiCall(DatatreeApi::QUERY_NO_PAGING,array($map));
			if(!$result['status']){
				$this->error($result['info']);
			}

			$this->assign("groups",$result['info']);
			$this->assign("store_id",$store_id);

			$result = apiCall(ProductGroupApi::QUERY_NO_PAGING,array(array('p_id'=>$id)));
			if(!$result['status']){
				$this->error($result['info']);
			}

			$groups =  $this->getTime($result['info']);
			$this->assign("addedgroups",$this->getGroups($result['info']));
			$this->assign("selectedgroups",$groups);
			$this->assign("id",$id);
			$this->display();
		}else{

		}
	}*/
	
	/**
	 * 商品运费设置
	 */
	public function express(){
		if(IS_GET){

			$id = I('get.id',0);

			$result = apiCall(ProductApi::GET_INFO, array(array('id'=>$id) ));

			if(!$result['status']){
				$this->error($result['info']);
			}
			
			if(is_null($result['info'])){
				$this->error("警告：商品信息获取失败！");
			}

            $product = $result['info'];

			$location = $product['loc_country'].">>".$product['loc_province'].">>".$product['loc_city'].">>".$product['loc_address'];
			
			$this->assign("store_id",$product['store_id']);
			$this->assign("location",$location);

			$this->assign("template_id",$product['template_id']);
			
			$result = apiCall(ProvinceApi::QUERY_NO_PAGING, array(array('countryid'=>1017) ));
			if($result['status']){
				$this->assign("province",$result['info']);
			}else{
				$this->error("警告：省份信息获取失败！");
			}

			
			$this->assign("countrylist",C('COUNTRY_LIST'));
			$this->assign("id",$id);
			$this->display();
		}else{

			$query = I('post.query','','htmlspecialchars_decode');
			$query = json_decode($query,JSON_UNESCAPED_UNICODE);

			$id = I('post.id','');
			if(empty($id)){
				$this->error("商品ID失效！");
			}

			$flag =  $query['islocchange'];
			$entity = array();
			if($flag){
				$entity['loc_country'] = $query['country'];
				$entity['loc_province'] = $query['province'];
                if($entity['loc_province'] == '请选择省份'){
                    $entity['loc_province'] = '';
                }
				$entity['loc_city'] = $query['city'];
				$entity['loc_address'] = $query['area'];
			}

			$templateid = intval($query['templateid']);

			$result = apiCall(ProductApi::SAVE_BY_ID, array($id,$entity));
			
			if(!$result['status']){
				$this->error($result['info']);
			}
			
			$this->success("操作成功！");
			
		}
	}


	/**
	 * 商品GROUP 管理
	 */
	public function productgroup(){

		if(I('product_code')){

			$id = I('get.id',0);
			$entity=array(
				'price'=>I('price'),
				'ori_price'=>I('ori_price'),
				'quantity'=>I('quantity'),
				'group_sum'=>I('product_code'),
			);
			$map['p_id'] = $id;
			$result = apiCall(ProductGroupApi::SAVE, array($map,$entity));
			if ($result['status']) {
				$this->success("添加成功");
			}else{
				$this->error("添加失败");
			}
		}else{
			$id = I('id',0);
			$result=apiCall(ProductGroupApi::GET_INFO,array(['p_id'=>$id]));
			$group_config=apiCall(GroupOrderApi::QUERY_NO_PAGING,array(['p_id'=>$id]));

			$this->assign("data", $result['info']);
			$this->assign("config", $group_config['info']);

			$this->assign("id", $id);

			$this->display();
		}
	}


	/**
	 * 商品GROUP 管理拼团配置管理
	 */
	public function groupconfig(){

		if(I('product_code')){

			$id = I('get.id',0);
			$price=I('price');
			$sum=I('product_code');
			$num=I('type');
			foreach($sum as $k => $v){
				if(!empty($v)){
					$entity=array(
							'price'=>$price[$k],
							'sum'=>$v,
							'p_id'=>$id,
							'type'=>$num[$k],
					);
					$map['p_id'] = $id;$map['type']=$num[$k];
					$vi = apiCall(GroupOrderApi::GET_INFO, array($map));
					dump($map);
					dump($vi);
					if(!empty($vi['info'])){
						$result = apiCall(GroupOrderApi::SAVE, array($map,$entity));
					}else{
						$result = apiCall(GroupOrderApi::ADD, array($entity));
					}
					if ($result['status']) {
					}else{
						$flag=true;
					}
				}
			}

			if($flag) $this->error('添加出错');

		}else{
			$id = I('id',0);

			$group_config=apiCall(GroupOrderApi::QUERY_NO_PAGING,array(['p_id'=>$id]));
			$this->assign("config", $group_config['info']);
			$this->assign("id", $id);
			$this->display();
		}
	}


	/**
	 * 商品SKU 管理
	 */
	public function sku(){
		
		if(IS_GET){
			$id = I('get.id',0);
			
			$result = apiCall(ProductApi::GET_INFO, array(array('id'=>$id) ));
			
			if(!$result['status']){
				$this->error($result['info']);
			}
            $product = $result['info'];
			if(is_null($product)){
				$this->error("警告：商品信息获取失败！");
			}

			//获取是否多规格
			$has_sku = apiCall(ProductSkuApi::HAS_SKU,array($id));

			if($has_sku['status']){
				$has_sku = $has_sku['info'];
			}else{
				$this -> error($has_sku['info']);
			}

			if($has_sku == 1) {
				//多规格
				$skuinfo = apiCall(ProductSkuApi::GET_SKU_ID, array($id,'sku_id'));

				if ($skuinfo['status']) {
					$skuinfo = $skuinfo['info'];
				} else {
					$this->error($skuinfo['info']);
				}

				$this->assign("skuinfo", $this->getSkuValue(json_decode($skuinfo, JSON_UNESCAPED_UNICODE)));

				$skulist = apiCall(ProductSkuApi::QUERY_NO_PAGING, array(array('product_id' => $id)));
				if ($skulist['status']) {
					$this->assign("skuvaluelist", json_encode($skulist['info'], JSON_UNESCAPED_UNICODE));
				}
			}else{
				//统一规格
				$res = apiCall(ProductSkuApi::GET_INFO,array(array('product_id'=>$id)));
				if($res['status']){
					$this -> assign('unify_price',$res['info']['price']);
					$this -> assign('unify_ori_price',$res['info']['ori_price']);
					$this -> assign('unify_quantity',$res['info']['quantity']);
					$this -> assign('unify_product_code',$res['info']['product_code']);
				}else{
					$this -> error($res['info']);
				}
			}


			$this->assign("has_sku", $has_sku);
			$this->assign("store_id", $result['info']['store_id']);


			$cate_id = $result['info']['cate_id'];

			$result = apiCall(SkuApi::QUERY_SKU_TABLE, array($cate_id));

			if ($result['status']) {
				$this->assign("skulist", $this->color2First($result['info']));
			}

			//SKU
			$result = apiCall(CategoryApi::GET_INFO, array(array('id' => $cate_id)));
			if (!$result['status']) {
				$this->error($result['info']);
			}
			$level = 0;
			$parent = 0;
			$preparent = -1;

			if (is_array($result['info'])) {
				$level = $result['info']['level'];
				$parent = $result['info']['parent'];
				$result = apiCall(CategoryApi::GET_INFO, array(array('id' => $parent)));
				if (!$result['status']) {
					$this->error($result['info']);
				}
				$preparent = $result['info']['parent'];
			}

			$this->assign("cate_id", $level);
			$this->assign("parent", $parent);
			$this->assign("preparent", $preparent);
			$this->assign("cate_id", $cate_id);
			$this->assign("id", $id);
			$this->display();

		}else{
			
			$id = I('post.id',0);
			$has_sku = I('post.has_sku',0);

			if($has_sku == 1){
				$sku_list = I('post.sku_list','');
				$sku_list = json_decode(htmlspecialchars_decode($sku_list),JSON_UNESCAPED_UNICODE);
			}else{
				$ori_price = I('post.ori_price',0);
				$price = I('post.price',0);
				$quantity = I('post.quantity',0);
				$product_code = I('post.product_code',"");
				$sku_list = array(
					'ori_price' => $ori_price,
					'price' => $price,
					'quantity' => $quantity,
					'product_code' => $product_code,
				);
			}

			$result = apiCall(ProductSkuApi::ADD_SKU_LIST, array($id,$has_sku,$sku_list));

			if(!$result['status']){
				$this->error($result['info']);
				
			}else{
				
				$this->success("保存成功！");

			}
		}
	}

	
	
	/**
	 * 
	 */
	private function getSkuValue($skuvalue){
		$valuelist = "";
		foreach($skuvalue as $value){
			foreach($value['vid'] as $vo){
				$valuelist = $valuelist.$vo.",";
			}
		}
		return $valuelist;
	}
	
	/**
	 * 商品详情页/新增
	 * @param $get.productid  商品ID
	 * @param $get.store_id 店铺ID
	 */
	public function detail(){
		if(IS_GET){
			//$productid = I('get.id','');
			$id = I('get.id',0);
			$store_id = I('get.store_id',0);
			if(empty($id)){
				$this->error("缺少商品ID");
			}
			if(empty($store_id)){
				$this->error("缺少店铺ID");
			}
			$map['id'] = $id;


			$result = apiCall(ProductApi::GET_INFO,array($map));
			//dump($result);
			if($result['status']){
				$detail = $result['info']['detail'];
				
			}else{
				$this->error("商品信息获取失败！");
			}
			//dump($detail);
			
			$this->assign("detail",$detail);
			$this->assign("id",$id);
			$this->assign("store_id",$store_id);
			//$this->assign("id",$id);
			$this->display();
			
		}else{
			$detail = I("post.detail",'');
			$id = I("post.id",'');

			$map['id'] = $id;

			$result = apiCall(ProductApi::SAVE,array($map,array('detail'=>$detail)));
			if($result['status']){
				$this->success("修改成功！");
			}else{
				$this->error($result['info']);
			}
		}
	}
	
	/**
	 * 首页/商品管理页面
	 */
	public function index() {
		$onshelf = I('onshelf', 0);
        $name = urldecode(I('name', '','urldecode'));

        //检测store_id 是否合法
        $result = apiCall(StoreApi::GET_INFO,array(array('id'=>$this->store_id,'uid'=>UID)));

        if(!$result['status']){
            $this -> error($result['info']);
        }

        if(is_null($result['info'])){
            $this -> error("店铺ID不合法!");
        }

        $params = array('onshelf' => $onshelf,'store_id'=>$this->store_id);

        $map = array();
        if (!empty($name)) {
            $map['name'] = array('like', '%'.$name.'%');
            $params['name'] = $name;
        }
        $map['onshelf'] = $onshelf;
        $map['status'] = 1;
        $map['store_id'] = $this->store_id;
        $page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
        $order = " createtime desc ";

        $result = apiCall(ProductApi::QUERY, array($map, $page, $order, $params));

		//
		if ($result['status']) {

			$this -> assign('name', $name);
			$this -> assign('onshelf', $onshelf);
			$this -> assign('p', I('get.p', 0));
			$this -> assign('store_id', $this->store_id);
			$this -> assign('show', $result['info']['show']);
			$this -> assign('list', $result['info']['list']);
			
			$store = apiCall(StoreApi::GET_INFO, array(array('id'=>$this->store_id)));
			if(!$store['status']){
				$this->error($store['info']);
			}
			$this->assign("store",$store['info']);
			$this -> display();
		} else {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error(L('UNKNOWN_ERR'));
		}
	}


    /**
     * 商品上下架
     * @internal param 删除成功后跳转 $success_url
     */
	public function shelf() {
		$status = I('get.on',0,'intval');
		$id = I('get.id', -1);
		$map = array('id' => $id);

		if($status == 1){
			$isSku = apiCall(ProductSkuApi::IS_SKU,array($id));

			if($isSku['status']){
//				if($isSku['info'] == 0){
//					$this -> error('请先填写商品规格信息!');
//				}
			}else{
				$this -> error($isSku['info']);
			}

			$result = apiCall(ProductApi::GET_INFO,array($map));
			$template_id = "";
			if($result['status']){
				$template_id = $result['info']['template_id'];
			}else{
				$this -> error($result['info']);
			}

			$result = apiCall(FreightTemplateApi::GET_INFO,array(array('id'=>$template_id)));
			if($result['status']){
				if($result['info'] == null){
					$this -> error('请选择运费模板信息!');
				}
			}else{
				$this -> error($result['info']);
			}
		}

		$entity['onshelf'] = $status;
		$result = apiCall(ProductApi::SAVE, array($map,$entity));
		
		if ($result['status'] === false) {
			LogRecord('[INFO]' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		} else {
			$this -> success(L('RESULT_SUCCESS'));
		}

	}

	/**
	 * 批量上下架
	 */
	public function shelfAll(){
		$ids = I('post.ids',-1);
		$status = I('post.status',-1,'intval');//此处status为0说明上架，为1说明下架
		if($ids === -1 || $status === -1){
			$this -> error("参数缺失");
		}
		if($status == 1){
			$status = 0;
		}else if($status == 0){
			$status = 1;
		}else{
			$this -> error("参数错误");
		}
		$error = false;
		if($status == 1){
			//上架前检查
			foreach($ids as $k => $v){
				$map = array(
					'id' => $v,
				);
				$isSku = apiCall(ProductSkuApi::IS_SKU,array($v));

				if($isSku['status']){
					if($isSku['info'] == 0){
						$error = '请先填写商品规格信息!id为'.$v;
						break;
					}
				}else{
					$this -> error($isSku['info']);
				}

				$result = apiCall(ProductApi::GET_INFO,array($map));
				$template_id = "";
				if($result['status']){
					$template_id = $result['info']['template_id'];
				}else{
					$this -> error($result['info']);
				}

				$result = apiCall(FreightTemplateApi::GET_INFO,array(array('id'=>$template_id)));
				if($result['status']){
					if($result['info'] == null){
						$error = '请选择运费模板信息!id为'.$v;
						break;
					}
				}else{
					$this -> error($result['info']);
				}

			}

		}
		if($error === false){
			//检查无误或者是下架
			$result = apiCall(ProductApi::SHELF_ALL,array($status,$ids));
			if($result['status']){
				$this -> success(L('RESULT_SUCCESS'));
			}else{
				LogRecord('[INFO]' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
				$this -> error($result['info']);
			}
		}else{
			$this -> error($error);
		}

	}

    /**
     * 单个删除
     * @param 删除成功后跳转|bool $success_url 删除成功后跳转
     */
	public function delete($success_url = false) {
		
		if ($success_url === false) {
			$success_url = U('Admin/Product/index',array('store_id'=>I('store_id',1)));
		}
		
		//TODO: 检测商品的其它数据是否存在
        $id = I('id', -1);
		$map = array('id' => $id);
		
		$result = apiCall(ProductApi::PRETEND_DELETE, array($map));


		
		if ($result['status'] === false) {
			LogRecord('[INFO]' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		} else {
            //1. 删除商品分组的
//            $result = apiCall(ProductGroupApi::DELETE,array(array('p_id'=>$id)));

			$this -> success(L('RESULT_SUCCESS'));
		}

	}

	/**
	 * 商品预创建－选择类目
	 */
	public function precreate() {
		
		if (IS_POST) {
			//保存
		} else {
			
			$map = array('parent'=>0);
			$result = apiCall(CategoryApi::QUERY_NO_PAGING, array($map));

            if (!$result['status']) {
                $this -> error($result['info']);
            }

			$store_id = I('get.store_id', 0);
			
			if ($store_id == 0) {
				$this -> error("缺少商铺ID参数");
			}

			$this -> assign("store_id", $store_id);
			if ($result['status']) {
				$this -> assign("rootcate", $result['info']);
			}
			$this -> display();
		}
	}

	/**
	 * 添加商品
	 *
	 */
	public function create() {

		if (IS_POST) {
			//1. 获取商品基础属性
			$base_attr = $this -> getBaseAttr();
			$img = $this -> getProductImg();
			$store_id = I('store_id', 0);
			//商品分组信息
			$product_group = I('product_group','');
			$group_start_time = I('group_start_time','');
			$group_start_time = strtotime($group_start_time);
			$group_end_time = I('group_end_time','');
			$group_end_time = strtotime($group_end_time);
			$group = array(
				'product_group' => $product_group,
				'group_start_time' => $group_start_time,
				'group_end_time' => $group_end_time,
			);
			if ($store_id == 0) {
				$this -> error("缺少商铺ID参数");
			}
			//限购
			if (I('post.isbuylimit', '0') == 1) {
				$buylimit = I('post.buylimit', 0);
			} else {
				$buylimit = 0;
			}
			$attr_ext = array(
					'post_free' => 1,
					'has_receipt' => I('post.has_receipt', 0),
					'under_guaranty' => I('post.under_guaranty', 0),
					'support_replace' => I('post.support_replace', 0),
					'total_sales' => I('post.total_sales', 0),
					'buy_limit' => $buylimit
			);
			$product = array('product_base' => $base_attr, 'attr_ext' => $attr_ext,'img' => $img,'group'=>$group);

			$result = $this -> addToProduct($store_id,  $product);

			if ($result['status']) {
				$this -> success("操作成功!", U('Admin/Product/index', array('store_id' => $store_id)));
			} else {
				$this -> error($result['info']);
			}

		} else {
			$catename = I('catename', '');
			$store_id = I('store_id', 0);
			$cates = I("cates", '');
			$cates = explode("_", $cates);
			if (count($cates) <= 1) {
				$this -> error("商品类目错误！");
			}

			$this -> assign("cate_id", $cates[count($cates)-1]);
			$this -> assign("store_id", $store_id);
			$this -> assign("catename", $catename);
			$this -> assign("cates", I('cates', ''));
			$this -> display();
		}
	}


	/**
	 * 商品信息编辑
	 */
	public function edit(){
		if(IS_GET){
			$onshelf=I('onshelf',0);
			$p=I('p',0);
			$id = I('get.id',0);
            $cate_id = I('get.cate_id','');
			$result = apiCall(ProductApi::DETAIL, array($id));
			if($result['status']){
				$this->assign("imgs",$result['info']['imgs']);
				$this->assign("vo",$result['info']);
			}
            $this->assign('cate_id',$cate_id);
			//类目列表
			$cate_name = array();
			while($cate_id != 0){
				$result = apiCall(CategoryApi::GET_INFO,array(array('id'=>$cate_id)));
				array_push($cate_name,$result['info']['name']);
				$cate_id = $result['info']['parent'];
			}
			$cate_name = array_reverse($cate_name);
			$this -> assign('cate_name',$cate_name);
			//查找分类
			$map = array(
				'p_id' => $id,
				'start_time' => array('elt',time()),
				'end_time' => array('egt',time())
			);
			$result = apiCall(ProductGroupApi::GET_INFO,array($map));
			if($result['status']){
				if(is_null($result['info'])){
					$this -> assign('product_group',0);
				}else{
					$this -> assign('product_group',$result['info']['g_id']);
					$this -> assign('group_start_time',$result['info']['start_time']);
					$this -> assign('group_end_time',$result['info']['end_time']);
				}
			}else{
				$this -> error($result['info']);
			}

			$this->assign('onshelf',$onshelf);
			$this->assign('p',$p);
			$this->display();
		}else{
			$onshelf=I('onshelf',0);
			$id = I('post.id',0);
			$buylimit = I('buylimit',0);
			if(empty($buylimit)){
				$buylimit = 0;
			}

			$weight = I('weight',0,'floatval');
            $goods_unit = I('post.dt_goods_unit','');
            $total_sales = I('post.total_sales',0,'intval');

			$img_list = explode(",",I('post.img', ''));
			array_pop($img_list);

			//商品分组信息
			$product_group = I('product_group','');
			$group_start_time = I('group_start_time','');
			$group_start_time = strtotime($group_start_time);
			$group_end_time = I('group_end_time','');
			$group_end_time = strtotime($group_end_time);
			$group = array(
					'product_group' => $product_group,
					'group_start_time' => $group_start_time,
					'group_end_time' => $group_end_time,
			);

			$img = array(
				'main_img' => I('main_img',''),
				'img_list' => $img_list,
			);

			$entity = array(
				'img'=> $img,
				'name'=>I('product_name',''),
                'dt_origin_country'=>I('post.dt_origin_country',''),
                'dt_goods_unit'=>$goods_unit,
				'synopsis'=>I('synopsis',''),
				'source'=>I('source',''),
				'weight'=>$weight,
				'total_sales'=>$total_sales,
				'buy_limit'=>$buylimit,
				'has_receipt' => I('post.has_receipt',0),
				'under_guaranty' => I('post.under_guaranty',0),
				'support_replace' => I('post.support_replace',0),
				'group' => $group,
			);

            $properties = $this->getProperties();

            if($properties !== false){
                $entity['properties'] = $properties;
            }

			$result = apiCall(ProductApi::SAVE_BY_ID,array($id,$entity));

			if(!$result['status']){
				$this->error($result['info']);
			}
			$this->assign('onshelf',$onshelf);

			$this->success(L('RESULT_SUCCESS'));
			
		}
	}

	/**
	 * 指定分类的所有属性
	 */
	public function cateAllProp() {

		if (IS_AJAX) {
			$cate_id = I('cate_id', 0);
			$map = array('cate_id'=>$cate_id);
			$result = apiCall(CategoryPropApi::QUERY_PROP_TABLE, array($map));
			
			if ($result['status']) {
				$this -> success($result['info']);
			} else {
				$this -> error($result['info']);
			}
		}
	}

    /**
     *
     * 采购入库
     *
     * 1. 第一次调用不会操作数据库
     * 2. 递归调用第二次才会改数据库
     *
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/30 20:20
     * @copyright by itboye.com
     * @param int $upload_wh 标识是否上报网仓
     */
    public function putin($upload_wh=0){
        if(IS_POST){

            $id = $this->_post("id",0,'缺少商品ID');
            $name = $this->_post("name",'');
            $has_sku = $this->_post("has_sku",0);
            $map = array(
                'id'=>$id,
            );

            $field = "quantity";

            //1. 上报网仓
            $data = array(
                'order_code'=>time(),
                'items'=>array(),
            );

            if($has_sku){

                $sku_id = $this->_post("sku_id",'');
                $putin_arr = $this->_post("putin",'');
                $quantity_arr = $this->_post("quantity",'');
                $map = array(
                    'product_id'=>$id,
                );
                foreach($sku_id as $key=>$vo){
                    $map['sku_id'] = $vo;
                    $putin = $putin_arr[$key];
                    $quantity = $quantity_arr[$key];
                    if($putin == 0){
                        continue;
                    }
                    if($putin > 0){

                        if($upload_wh) {
                            $result = apiCall(ProductSkuApi::SET_INC, array($map, $field, $putin));
                        }
                    }elseif($putin < 0){
                        //减去SET_DEC 需要传入的正数
                        $putin = 0-$putin;
                        if($quantity - $putin < 0){
                            $putin = $quantity;
                        }

                        if($upload_wh) {
                        $result = apiCall(ProductSkuApi::SET_DEC,array($map,$field,$putin));
                        }
                        $putin = 0 - $putin;
                    }

                    array_push($data['items'],array(
                        'id'=>$id,
                        'name'=>$name,
                        'product_code'=>$vo,
                        'count'=>$putin,
                    ));

                }
            }else{
                $putin = $this->_post("putin",0,"不能为0");
                $quantity = $this->_post("quantity",0);

                if($putin > 0){
                    if($upload_wh){
                        $result = apiCall(ProductApi::SET_INC,array($map,$field,$putin));
                    }
                }elseif($putin < 0){
                    $putin = 0 - $putin;
                    if($quantity - $putin < 0){
                        $putin = $quantity;
                    }
                    if($upload_wh) {
                        $result = apiCall(ProductApi::SET_DEC,array($map,$field,$putin));
                    }
                    $putin = 0 - $putin;
                }

                array_push($data['items'],array(
                    'id'=>$id,
                    'name'=>$name,
                    'product_code'=>$id,
                    'count'=>$putin,
                ));
            }



            //id,name,product_code,count
            if($upload_wh == 0) {
                $request = new WHPurcharseOrder();
                $upload_result = $request->request($data);
                if($upload_result['status'] == 0){

                    $this->putin(1);

                    $this->success("操作成功!");

                }else{
                    $this->error($upload_result['info']);
                }
            }else{
                $this->success("操作成功!");
            }



        }else{

            $id = $this->_get('id',0,'缺少商品ID');

            $result = apiCall(ProductApi::DETAIL, array($id));

            if ($result['status']) {
                $product = $result['info'];

                $sku_list = $this -> getSkuList($product);
                $this->assign("sku_list",$sku_list['sku_list']);
                $this->assign("product",$product);

                $this -> display();
            } else {
                LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                $this -> error(L('UNKNOWN_ERR'));
            }
        }
    }
		
	//==========================私有方法
//
    private function getSkuList($product) {

        $skuinfo = json_decode($product['sku_info']);
        $sku_ids = array('-1');
        $sku_value_ids = array('-1');
        foreach ($skuinfo as $vo) {
            array_push($sku_ids, $vo -> id);
            foreach ($vo->vid as $vid) {
                array_push($sku_value_ids, $vid);
            }
        }

        $map = array();
        $map['id'] = array('in', $sku_ids);

        $result = apiCall(SkuApi::QUERY_NO_PAGING, array($map));
        if (!$result['status']) {
            $this -> error($result['info']);
        }
        $sku_result = $result['info'];

        $map = array();
        $map['id'] = array('in', $sku_value_ids);

        $result = apiCall(SkuvalueApi::QUERY_NO_PAGING, array($map));
        if (!$result['status']) {
            $this -> error($result['info']);
        }
        $sku_value_result = $result['info'];
        //上述代码获取SKU以及SKU值的名称

        $sku_arr = array();
        foreach ($sku_result as $_sku) {
            $key = $_sku['id'] . ':';
            foreach ($sku_value_result as $_sku_value) {
                if ($_sku_value['sku_id'] == $_sku['id']) {

                    if (!isset($sku_arr[$_sku['id']])) {
                        $sku_arr[$_sku['id']] = array('id' => $_sku['id'], 'sku_name' => $_sku['name'], 'sku_value_list' => array());
                    }

                    array_push($sku_arr[$_sku['id']]['sku_value_list'], array('id' => $_sku_value['id'], 'name' => $_sku_value['name']));

                }
            }
        }

        $result = apiCall(ProductSkuApi::QUERY_NO_PAGING, array( array('product_id' => $product['id'])));
        if (!$result['status']) {
            $this -> error($result['info']);
        }

        $formatSku = array();
        foreach ($result['info'] as &$vo) {
            $formatSku[$vo['sku_id']] = array('id'=>$vo['id'],'icon_url' => getImageUrl($vo['icon_url']), 'ori_price' => $vo['ori_price'], 'price' => $vo['price'], 'product_code' => $vo['product_code'], 'product_id' => $vo['product_id'], 'quantity' => $vo['quantity'], );
            $formatSku[$vo['sku_id']]['sku_desc'] = $this->getSkuDesc($vo['sku_id'],$sku_arr);
        }

        return array('sku_list' => $formatSku, 'sku_arr' => $sku_arr);
    }

    private function getSkuDesc($sku_id,$sku_arr){
        $sku_list = explode(";",$sku_id);
        $sku_desc = "";
        foreach($sku_list as $sku_item){
            $sku_value = explode(":",$sku_item);
            $flag = false;
            foreach($sku_arr as $key=>$sku){
                if($key == $sku_value[0]){
                    $sku_desc .= $sku['sku_name'];
                    $flag = true;

                    foreach($sku['sku_value_list'] as $sku_value_item){
                        if($sku_value_item['id'] == $sku_value[1]){
                            $sku_desc .= ':'.$sku_value_item['name'];
                        }
                    }
                }
            }
            if($flag){
                $sku_desc .= ';';
            }
        }

        return $sku_desc;
    }

    /**
     * 将产品信息保存到数据库
     * @param $store_id
     * @param $product
     * @return mixed
     */
	private function addToProduct($store_id, $product) {

		$product_base = $product['product_base'];
		$attr_ext = $product['attr_ext'];
		$group = $product['group'];

		$entity = array(
				'uid'=>UID,
				'store_id' => $store_id,
				'template_id' => '',
				'onshelf' => '0',
				'status' => 1,
				'has_receipt' => $attr_ext['has_receipt'],
				'under_guaranty' => $attr_ext['under_guaranty'],
				'support_replace' => $attr_ext['support_replace'],
				'total_sales' => $attr_ext['total_sales'],
				'buy_limit' => $attr_ext['buy_limit'],
				'img' => $product['img'],
				'group' => $group,
		);

		$entity = array_merge($entity,$product_base);


		$result = apiCall(ProductApi::ADD, array($entity));
		return $result;
	}

	/*private function addToProduct($store_id, $product) {

		$tariff_code = I('post.tariff_code','');
		$product_base = $product['product_base'];
		$attr_ext = $product['attr_ext'];

		$entity = array(
				'uid'=>UID,
				'dt_tariff_code'=>$tariff_code,
				'store_id' => $store_id,
				'has_sku' => 0,
				'template_id' => '',
				'detail' => '',
				'onself' => '0',
				'status' => 1,
				'post_free' => $attr_ext['post_free'],
				'has_receipt' => $attr_ext['has_receipt'],
				'under_guaranty' => $attr_ext['under_guaranty'],
				'support_replace' => $attr_ext['support_replace'],
				'total_sales' => $attr_ext['total_sales'],
		);

		$entity = array_merge($entity,$product_base);

		$entity['ori_price'] = $product['sku']['ori_price'];
		$entity['weight'] = $product['sku']['weight'];
		$entity['price'] = $product['sku']['price'];
		$entity['quantity'] = $product['sku']['quantity'];
		$entity['product_code'] = $product['sku']['product_code'];


		$result = apiCall(ProductApi::ADD, array($entity));
		return $result;
	}*/

	/**
	 * 获取商品图片信息
	 */
	private function getProductImg(){
		//1. 主图
		$main_img = I('post.main_img', '');

		//2. 商品轮播图
		$img_list = array();

		$img = explode(",", I('post.img', ''));

		foreach ($img as $vo) {
			if ($vo) {
				$img_list[] = $vo;
			}
		}

		return array(
			'img_list' => $img_list,
			'main_img' => $main_img,
		);
	}
    /**
     *
     *
     * @return array
     */
	private function getBaseAttr() {

		$cates = I("post.cates", '');
		$cates = explode("_", $cates);

		//1. 类目必须大于2层
		if (count($cates) <= 1) {
			$this -> error("商品类目错误！");
		}

		//2. 属性

		$properties = $this->getProperties();
		if($properties === false){
			$properties = "";
		}
//        dump($properties);
		//2.1 取最后一个类目
		$category = $cates[count($cates) - 1];

		$synopsis = I('post.synopsis','');
		$name = I('post.product_name','');
		$dt_origin_country = I('post.dt_origin_country','');
		$weight = I('post.weight',0,'floatval');

		$dt_goods_unit = I('dt_goods_unit',"001");

		return array(
				'weight'=>$weight,
				'name' => $name,
				'synopsis'=>$synopsis,  //简介
				'dt_origin_country'=>$dt_origin_country,   //产地编码
				'cate_id' => $category,
				'detail' => "",
				'properties' => $properties,
				'loc_country' => '中国',
				'loc_province' => '	',
				'loc_city' => '',
				'loc_address' => '',
				'dt_goods_unit' => $dt_goods_unit
		);
	}

/*	private function getBaseAttr() {

		$cates = I("post.cates", '');
		$cates = explode("_", $cates);

		//1. 类目必须大于2层
		if (count($cates) <= 1) {
			$this -> error("商品类目错误！");
		}

		//2. 属性

		$properties = $this->getProperties();
		if($properties === false){
			$properties = "";
		}
//        dump($properties);
		//2.1 取最后一个类目
		$category = $cates[count($cates) - 1];

		//3. 主图
		$main_img = I('post.main_img', '');

		//4. 限购
		if (I('post.isbuylimit', '0') == 1) {
			$buylimit = I('post.buylimit', 0);
		} else {
			$buylimit = 0;
		}

		//5. 商品轮播图
		$img_list = array();

		$img = explode(",", I('post.img', ''));

		foreach ($img as $vo) {
			if ($vo) {
				$img_list[] = $vo;
			}
		}
		$img_post = I('post.img_post', '');
		$img_post_bg = I('post.img_post_bg', '');
		$synopsis = I('post.synopsis','');
		$name = I('post.name','');
		$source = I('post.source','');
		$dt_origin_country = I('post.dt_origin_country','');
		$weight = I('post.weight',0,'floatval');

		//4. SKU
		$sku_info = array();
		//
		return array(
				'weight'=>$weight,
				'name' => $name,
				'synopsis'=>$synopsis,  //简介
				'source'=>$source,   //产地
				'dt_origin_country'=>$dt_origin_country,   //产地编码
				'cate_id' => $category,
				'img' => $img_list,
				'main_img' => $main_img,
				'img_post'=>$img_post,
				'img_post_bg'=>$img_post_bg,
				'datail' => "",
				'properties' => $properties,
				'sku_info' => $sku_info,
				'buy_limit' => $buylimit,
				'loc_country' => '中国',
				'loc_province' => '	',
				'loc_city' => '',
				'loc_address' => ''
		);
	}*/

    private function getProperties(){
        $property = I('post.property', '');
        if(empty($property)){
            return false;
        }
        $property = explode(";", $property);
        $properties = array();

        foreach ($property as $vo) {
            $prop = explode(",", $vo);
            if (count($prop) == 2) {
                $properties[] = array('id' => $prop[0], 'vid' => $prop[1]);
            }
        }
        $properties = json_encode($properties);
        return $properties;
    }

    /**
	 * 将颜色SKU 放在最前面
	 */
	private function color2First($skulist){
		$colorIndex = 0;
		for($i=0;$i<count($skulist);$i++){
			if($skulist[$i]->name == "颜色"){
				$colorIndex = $i;
				break;
			}
		}
		
		if($colorIndex > 0){
			$temp = $skulist[0];
			$skulist[0] = $skulist[$colorIndex];
			$skulist[$colorIndex] = $temp;
		}
		return $skulist;
		
	}


	public function view(){
		$result=apiCall(UserPictureApi::GET_INFO,array(array('id'=>I('imgId'))));
		$this->assign('img',$result['info']['path']);
		$this->display();
	}


	/**
	 * 商品咨询
	 */
	public function faq(){
		$startdatetime = I('startdatetime',date('Y/m/d H:i',time()-24*3600*30),'urldecode');
		$enddatetime = I('enddatetime',date('Y/m/d H:i',time()),'urldecode');

		$startdatetime = urldecode($startdatetime);
		$enddatetime = urldecode($enddatetime);

		$pid = I('get.pid',-1);
		$tobereply = I('get.tobereply');

		//分页时带参数get参数
		$params = array(
			'startdatetime'=>$startdatetime,
			'enddatetime'=>$enddatetime
		);

		$map = array();

		if($pid!=-1){
			$map['pid'] = $pid;
			$params['pid']= $pid;
		}

		if($tobereply=='yes'){
			$map['reply_time'] = 0;
		}

		$startdatetime = strtotime($startdatetime);
		$enddatetime = strtotime($enddatetime);

		if($startdatetime === FALSE || $enddatetime === FALSE){
			LogRecord('INFO:'.$result['info'],'[FILE] '.__FILE__.' [LINE] '.__LINE__);
			$this->error(L('ERR_DATE_INVALID'));
		}

		$map['ask_time'] = array(array('EGT',$startdatetime),array('elt',$enddatetime),'and');

		$page = array('curpage' => I('get.p', 0), 'size' => 15);
		$order = "ask_time desc";
		//
		$result = apiCall(ProductFaqApi::QUERY,array($map,$page,$order,$params));
		//
		if($result['status']){
			$ProductFaq = $result['info'];

			//查询商品名称
			foreach($ProductFaq['list'] as &$value){
				$result = apiCall(ProductApi::GET_INFO,array(array('id'=>$value['pid'])));
				if($result['status']){
					$value['product_name'] = $result['info']['name'];
				}else{
					$this->error('异常错误');
				}
			}

			$this->assign('startdatetime',$startdatetime);
			$this->assign('enddatetime',$enddatetime);
			$this->assign('show',$ProductFaq['show']);
			$this->assign('list',$ProductFaq['list']);


			$this->display();
		}else{
			LogRecord('INFO:'.$result['info'],'[FILE] '.__FILE__.' [LINE] '.__LINE__);
			$this->error(L('UNKNOWN_ERR'));
		}
	}
	/**
	 * 删除FAQ
	 */
	public function deleteFaq(){

		$map = array('id' => I('id', -1));
		$result = apiCall(ProductFaqApi::DELETE,array($map));

		if($result['status']){
			$this -> success(L('RESULT_SUCCESS'));
		}else{
			LogRecord('[INFO]' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this->error($result['info']);
		}

	}

	/**
	 * 批量删除FAQ
	 */
	public function bulkDeleteFaq(){
		$ids = I('ids', -1);
		if ($ids === -1) {
			$this -> error(L('ERR_PARAMETERS'));
		}
		$ids = implode(',', $ids);
		$map = array('id' => array('in', $ids));

		$result = apiCall(ProductFaqApi::DELETE,array($map));

		if($result['status']){
			$this -> success(L('RESULT_SUCCESS'));
		}else{
			LogRecord('[INFO]' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this->error($result['info']);
		}

	}

	/**
	 * 回复FAQ
	 */
	public function replyFaq(){
		if(IS_POST){

			$id = I('post.id',-1);
			if($id==-1){
				$this->error('参数错误！');
			}
			$map = array(
				'id'=>$id,
			);
			$entity = array(
				'reply_content'=>I('post.reply_content',''),
				'reply_uid'=>UID,
				'reply_username'=>'森森',
				'reply_time'=>NOW_TIME
			);
			$result = apiCall(ProductFaqApi::SAVE,array($map,$entity));
			if($result['status']){
				$this->success('保存成功！');
			}else{
				$this->error($result['info']);
			}


		}else{

			$id = I('get.id',-1);
			if($id==-1){
				$this->error('参数错误！');
			}
			$map = array(
				'id'=>$id
			);
			$result = apiCall(ProductFaqApi::GET_INFO,array($map));

			if($result['status']){

				$faq = $result['info'];
				$this->assign('faq',$faq);

			}else{
				$this->error($result['info']);
			}

			$this->display();

		}


	}
}
